<?php

namespace App\Models\Factory\V2;


use App\Helpers\RestUtils;
use App\Helpers\Utils;
use App\Models\AbsModelFactory;
use App\Models\Factory\UserFactory;
use App\Models\Orm\Collection;
use App\Models\Orm\CooperativeCompany;
use App\Models\Orm\DataProductApply;
use App\Models\Orm\DataProductDetail;
use App\Models\Orm\DataProductDetailLog;
use App\Models\Orm\PlatFormDetail;
use App\Models\Orm\Product;
use App\Models\Orm\ProductLabels;
use App\Models\Orm\Recommend;
use App\Models\Orm\ProductDeliveryurl;


/**
 * 关于产品的工厂
 * Class ProductFactory
 * @package App\Models\Factory
 */
class ProductFactory extends AbsModelFactory
{
    /**
     * 查询产品链接状态
     * @param 
     * $id       int 产品id
     * $linkType int 链接类型 (1，安稳钱包链接 2，安卓链接 3，IOS链接 4，微信链接 5，短信链接)
     */
    public static function getlink($id,$linkType)
    {
        $data = ProductDeliveryurl::select('*')
                ->where('product_id', $id)
                ->where('type', $linkType)
                ->where('status', 1)
                ->first();
        if($data) {
            $url = $data->url;
            if(!empty($url))
            return $data;
        }
        return false;
    }
    /**
     * 筛选
     * @param $identity
     * @param $labels
     * @param $amount
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public static function screening($identity, $labels, $amount, $linkType)
    {

        //拿到$labels 去找数据库符合他的条件的product_id
        //取出product_id的交集

        $lable_count = count($labels);


        $product_id = ProductLabels::select('product_id')
            ->whereIn('labels_id', $labels)
            ->get()->toArray();

        $product_id = array_column($product_id, 'product_id');

        $product_id_count = array_count_values($product_id);

        $res = [];

        foreach ($product_id_count as $key => $value) {
            if ($value == $lable_count) {
                $res[$key]['product_id'] = $key;
            }
        }


        $query = Product::with('labels')->select(['pname', 'id', 'product_introduction', 'product_logo', 'min_algorithm', 'interest_algorithm', 'fastest_time', 'maximum_amount','minimum_amount'])
            ->where('maximum_amount', '>=', $amount)->where('status',1)->where('vip_level',0);


        if (empty($identity) && empty($labels)) {//如果传过来的身份数据为空

            $product = $query->get();

        } elseif (!(empty($identity)) && empty($labels)) {

            $product = $query->where('crowd', 'like', '%' . $identity . '%')
                             ->get();

        } elseif (empty($identity) && !(empty($labels))) {

            $product = $query->whereIn('id', $res)->get();

        } elseif (!(empty($identity)) && !(empty($labels))) {

            //根据身份查询
            $product = $query->where('crowd', 'like', '%' . $identity . '%')
                             ->whereIn('id', $res)
                             ->get();
        }
        $productdata = [];
        // 添加产品多链接状态筛选条件
        foreach ($product as $k => $v) {
            if(self::getlink($v['id'], $linkType)) {
                $productdata[] = $product[$k];
            }
        }

        return $productdata;

    }

    /**
     * 热门推荐和新品上线
     * @return array
     */
    public static function HotNew($linkType)
    {
        $query = Product::with('labels')->select(['pname', 'product.id', 'product_introduction', 'product_logo', 'min_algorithm', 'interest_algorithm', 'fastest_time', 'maximum_amount','activity','online','minimum_amount'])->where('vip_level',0);
         //热门产品查询
        $hot = $query->join('recommend','product.id', '=', 'recommend.product_id')
                ->where('status',1)
                ->orderBy('sort','asc')
                ->get()
                ->toArray();
        //$hot = $query->where('status',1)->whereIn('id',$recomment_product_id)->limit(10)->get()->toArray();

        $recomment_product_id = Recommend::select('product_id')
                                            ->orderBy('sort','asc')
                                            ->get()
                                            ->toArray();

        $recomment_product_id = array_column($recomment_product_id,'product_id');
        
        //计算符合条件的热门推荐产品个数
        $hotId = Product::select('id')->where(['status'=>1,'online'=>1])->whereIn('id',$recomment_product_id)->limit(10)->get()->toArray();

        if($hotId) {
            foreach ($hotId as $k => $v) {
                $ids[] = $v['id'];
            }
        }else{
            $ids =[];
        }

        //新品上线
        $new = $query = Product::with('labels')->select(['pname', 'id', 'product_introduction', 'product_logo', 'min_algorithm', 'interest_algorithm', 'fastest_time', 'maximum_amount','activity','online','minimum_amount'])->where(['online'=>1,'status'=>1,'vip_level'=>0])->whereNotIn('id',$ids)->get()->toArray();

        $data = array_merge($hot,$new);
        $productdata = [];
        // 添加产品多链接状态条件
        foreach ($data as $k => $v) {
            if(self::getlink($v['id'], $linkType)) {
                $productdata[] = $data[$k];
            }
        }

        return $productdata;
    }



    /**
     * 查看产品详情
     */
    public static function productDetail($id, $token = "", $linkType = "")
    {

        $product = Product::with('labels')->where('id', $id)->where('status',1)->first()->toArray();
        if (!$product){
            return [];
        }
        // 添加产品安稳钱包链接
        $producturl = self::getlink($product['id'], $linkType);
        if(!isset($producturl->url)) return [];
        $product['link'] = $producturl->url;

        $pl_id = $product['pl_id'];

        if (!empty($token)) {
            $user = UserFactory::getUserByToken($token);
            //判断用户token是否过期
            if($user){
                $result = Collection::where(['uid' => $user ->id, 'product_id' => $id])->first();
                if ($result) {
                    $product['collectioStatus'] = 1;

                } else {
                    $product['collectioStatus'] = 2;
                }
            }else
            {
                //如果token过期就重新给一个状态,字段自己判断一下,然后扫除token
                $product['collectioStatus'] = 3;
            }

        }
        /*$platform = PlatFormDetail::select('pl_name','registered_time')->where('pl_id', $pl_id)->get();
        $platform = $platform->toArray();
        $platform = $platform[0];
        $product['platformdetail'] = $platform;*/

        /* 新平台表->公司表 开始 */
        $company = CooperativeCompany::select('company_name as pl_name', 'founding_time as registered_time')->find($pl_id)->toArray();
        $product['platformdetail'] = $company;
        /* 新平台表->公司表 结束 */

        //var_dump($product);
        //die;interest_algorithm
        //switch ($product['interest_algorithm']) {
        //case 0:
        //$product['interest_algorithm'] = '日利率';
        //break;
        //            case 1:
        //$product['interest_algorithm'] = '月利率';
        //break;
        //        }

        switch ($product['review']) {
            case 0:
                $product['review'] = '自动审核';
                break;
            case 1:
                $product['review'] = '人工审核';
                break;
            case 2:
                $product['review'] = '线下审核';
                break;
        }


        switch ($product['repayment']) {
            case 0:
                $product['repayment'] = '等额本息';
                break;
            case 1:
                $product['repayment'] = '等额本金';
                break;
            case 2:
                $product['repayment'] = '一次性还款';
                break;
            case 3:
                $product['repayment'] = $product['repayments'];
                break;
        }

        switch ($product['repayment_channels']) {
            case 0:
                $product['repayment_channels'] = 'ATM还款';
                break;
            case 1:
                $product['repayment_channels'] = '手机银行还款';
                break;
            case 2:
                $product['repayment_channels'] = 'APP还款';
                break;
            case 3:
                $product['repayment_channels'] = '其他';
                break;
        }

        switch ($product['prepayment']) {
            case 0:
                $product['prepayment'] = '不可以';
                break;
            case 1:
                $product['prepayment'] = '可以';
                break;
            case 2:
                $product['prepayment'] = $product['prepayments'];
                break;

        }

        switch ($product['actual_account']) {
            case 0:
                $product['actual_account'] = '全部到账';
                break;
            case 1:
                $product['actual_account'] = '扣除手续费';
                break;
            case 2:
                $product['actual_account'] = '扣除手续费和利息';
                break;
            case 3:
                $product['actual_account'] = $product['actual_accounts'];
                break;

        }

        $product['crowds'] = explode(',', $product['crowd']);
        $uu = '';
        foreach ($product['crowds'] as $u) {
            switch ($u) {
                case 1:
                    $uu = '上班族';
                    break;
                case 3:
                    $uu .= ' 逍遥客';
                    break;
                case 4:
                    $uu .= ' 企业主';
                    break;
                case 2:
                    $uu .= ' 其他';
                    break;
            }
        }
        $product['crowd'] = $uu;


        $product['use'] = explode(',', $product['use']);
        $uu1 = '';
        foreach ($product['use'] as $u) {
            switch ($u) {
                case 0:
                    $uu1 = '秒贷现金';
                    break;
                case 1:
                    $uu1 .= '、还信用卡';
                    break;
                case 2:
                    $uu1 .= '、消费分期';
                    break;
            }
        }
        $product['use'] = $uu1;
        return $product;
    }


    //产品详情
    public static  function getPlatform($id)
    {
        $result = Product::where('id',$id)->where('status',1)->first();

        return $result ? $result : false;
    }
    //插入产品流水

    public static  function addProductDetail($data,$product)
    {
        $data['platform_id'] = $product->pl_id;
        $data['platform_product_id'] = $product ->id;
        $data['platform_product_name'] = $product -> pname;
        $data['create_ip'] = Utils::ipAddress();
        $data['create_at'] = date('Y-m-d H:i:s',time());
        $result = DataProductDetailLog::create($data);
        return $result? true :false;
    }

    //插入产品流水表
    public static  function addProductApply($data,$product)
    {
        $data['platform_id'] = $product->pl_id;
        $data['platform_product_id'] = $product ->id;
        $data['platform_product_name'] = $product -> pname;
        $data['create_ip'] = Utils::ipAddress();
        $data['create_at'] = date('Y-m-d H:i:s',time());
        $result = DataProductApply::create($data);
        return $result? true :false;
    }
}
